package org.moriwuzhe.shuttle.spring.utils;

import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import java.util.HashSet;
import java.util.Set;

public class ClassUtil {

    public static Set<Class<?>> scanPackage(String packageName) {
        final Set<Class<?>> classes = new HashSet<>();
        try {
            final PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(Thread.currentThread().getContextClassLoader());
            final String packagePath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + packageName.replace(".", "/") + "/**/*.class";
            final Resource[] resources = resolver.getResources(packagePath);
            if (resources.length == 0) {
                return classes;
            }
            for (Resource resource : resources) {
                final String url = resource.getURI().toString();
                final int start = url.lastIndexOf(packageName.replace(".", "/"));
                final int end = url.lastIndexOf(".class");
                String name = url.substring(start, end);
                name = name.replace("/", ".");
                final Class<?> clazz = Thread.currentThread().getContextClassLoader().loadClass(name);
                if (clazz.isInterface()) {
                    continue;
                }
                classes.add(clazz);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return classes;
    }

    public static void main(String[] args) {
        Set<Class<?>> classes = scanPackage("org.moriwuzhe");
        System.out.println(classes);
        for (Class<?> aClass : classes) {
            System.out.println(aClass.getSimpleName());
        }
    }
}
